/**
 * Created by lwy on 2017/8/16.
 */

var goodsCategoryLevel;
var page = 1;
var parentCategoryId = $('#twoLEvel').val();
var categoryId = '';
//获取父菜单
$(function(){
    doOneLevel();
    doAjax();
})

function doOneLevel() {
    $.ajax({
        url:'/crm/goodsCategoryC/firstLevel.json',
        dataType:'json',
        data:{},
        type:'post',
        success:function (data) {
            for(var i=0;i<data.datas.length;i++){
                $('<option value="'+data.datas[i].id+'">'+data.datas[i].name+'</option>').appendTo($('#twoLEvel'))
            }
            $('#twoLEvel').change(function () {
                doTwoLevel();
                parentCategoryId = $('#twoLEvel').val();
            })
        }
    })
}

function doTwoLevel() {
    $.ajax({
        url:'/crm/goodsCategoryC/secondLevel.json',
        dataType:'json',
        data:{
            parentCategoryId:$('#faMenu').val(),
        },
        type:'post',
        success:function (data) {
            $('#erjiLEvel').empty();
            $('<option value="">请选择</option>').appendTo($('#erjiLEvel'));
            for(var i=0;i<data.datas.length;i++){
                $('<option value="'+data.datas[i].id+'">'+data.datas[i].name+'</option>').appendTo($('#erjiLEvel'))
            }
            $('#erjiLEvel').change(function () {
                parentCategoryId = $('#erjiLEvel').val();
            })
        }
    })
}

function doAjax(){
    $.ajax({
        url:'/crm/goodsCategoryC/search.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('crmtoken'),
            pageNu:page,
            name:$('#name').val(),
            level:$('#type').val(),
            parentCategoryId:parentCategoryId,
            IsValid:$('#state').val(),
        },
        type:'post',
        success: function (data) {
            if(data.code==-1){
                window.parent.location.href="/crm/login.jsp"
            }
            if(data.code==0){
                alert(data.msg);
            }
            if(data.code==1){
                $('#record').html(data.recordsTotal);
                $('#withdraw-record').empty();
                var datas = data.datas.categoryList;
                for(var i=0;i<datas.length;i++){
                    $('<tr class="gradeA odd">'+
                        '<a href=""><td class="sorting_1 withdrawId" data-toggle="modal" data-target="#modal4" style="text-decoration: underline;cursor: pointer;" id="'+datas[i].id+'">'+datas[i].id+'</td></a>'+
                        '<td class="sorting_1">'+datas[i].name+'</td>'+
                        '<td class="sorting_1">'+datas[i].summary+'</td>'+
                        '<td class=" ">'+datas[i].level+'</td>'+
                        '<td class=" ">'+datas[i].parentCategoryName+'</td>'+
                        '<td class=" ">'+datas[i].isValid+'</td>'+
                        '<td class=" ">'+datas[i].sort+'</td>'+
                        '<td class=" ">'+datas[i].createUserName+'</td>'+
                        '<td class=" ">'+datas[i].createTime+'</td>'+
                        '</tr>').appendTo($('#withdraw-record'));
                }
                //id处理
                $('.withdrawId').click(function(){
                    var id = $(this).html();
                    categoryId = id,
                    $.ajax({
                        url:'/crm/goodsCategoryC/getById.json',
                        dataType:'json',
                        data:{
                            token:localStorage.getItem('crmtoken'),
                            id:id,
                        },
                        type:'post',
                        success:function (data) {
                            if(data.code==1){
                                var editData = data.datas.goodsCategory;
                                $('#editName').val(editData.name);
                                $('#editsummary').val(editData.summary);
                                $('#editState').val(editData.isValid);
                                $('#editlinkUrl').val(editData.linkUrl);
                                $('#mainImg2').attr('src',editData.imgUrl)
                                $('#editNumber').val(editData.sort);

                            }
                        }
                    })
                })
                $(".pagination").createPage({
                    totalPage:data.datas.totalPage,
                    currPage:data.datas.pageNo,
                    pageCount:data.datas.pageNo,
                    turndown:'true',
                    backFn:function(p){
                        page=p;
                        doAjax();
                    }
                });
            }
        }
    })
}

//查询
$('#refer').click(function(){
    page=1;
    doAjax();
})
var addParentCategoryId = '';
//分类级别选择一级分类，上级分类id隐藏
$('#addType').change(function(){
    if($('#addType').val()==1){
        $('#imageHead').css({'width':'522px','height':'175px'});
        $('#cateGoryImgBox').show();
    }else if($('#addType').val()==2){
        doLevel1();
        $('#cateGoryImgBox').hide();
        $('#addfaBox').show();
    }else if($('#addType').val()==3){
        doLevel1();

        $('#imageHead').css({'width':'144px','height':'144px'});

        $('#imageHead').css({'width':'522px','height':'175px'});

        $('#addfaBox,#addfaBox2,#cateGoryImgBox').show();
    }
})

function doLevel1() {
    $.ajax({
        url:'/crm/goodsCategoryC/firstLevel.json',
        dataType:'json',
        data:{},
        type:'post',
        success:function (data) {
            for(var i=0;i<data.datas.length;i++){
                $('<option value="'+data.datas[i].id+'">'+data.datas[i].name+'</option>').appendTo($('#addfaMenu'))
            }
            $('#addfaMenu').show();
        }
    })
}
$('#addfaMenu').change(function () {
    addParentCategoryId = $('#addfaMenu').val();
    if($('#addType').val()==3){
        doLevel2();
    }
})
function doLevel2() {
    $.ajax({
        url:'/crm/goodsCategoryC/secondLevel.json',
        dataType:'json',
        data:{
            parentCategoryId:$('#addfaMenu').val(),
        },
        type:'post',
        success:function (data) {
            $('#addfaMenu2').empty();
            $('<option value="">请选择</option>').appendTo($('#addfaMenu2'));
            for(var i=0;i<data.datas.length;i++){
                $('<option value="'+data.datas[i].id+'">'+data.datas[i].name+'</option>').appendTo($('#addfaMenu2'))
            }
            $('#addfaMenu2').change(function () {
                addParentCategoryId = $('#addfaMenu2').val();
            })
        }
    })
}

$(document).on('click','.del',function () {
    $(this).siblings().attr('src','../static/img/uploadImg.png');
    $(this).parent().empty().hide();
})

//添加
$('#addSave').click(function(){
    $.ajax({
        url:'/crm/goodsCategoryC/toAdd.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('crmtoken'),
            name:$('#addName').val(),
            imgUrl:$('#mainImg').attr('src'),
            categoryType:1,
            parentCategoryId:addParentCategoryId,
            summary:$('#summary').val(),
            number:$('#number').val(),
            linkUrl:$('#linkUrl').val(),
            sort:$('#number').val(),
            level:$('#addType').val(),
        },
        type:'post',
        success:function(data){
            if(data.code==0){
                alert(data.msg)
                return;
            }
            if(data.code==-1){
                window.parent.location.href="/crm/login.jsp"
            }
            if(data.code==1){
                alert('添加成功');
                $('#myModal5').removeClass('fade in');
                $('#myModal5').addClass('fade');
                $('#myModal5').attr('aria-hidden',true);
                $('#myModal5').css('display','none');
                $('.modal-backdrop').css('display','none');
                $('#myModal5 input').val('');
                page=1;
                doAjax();
            }
        }
    })
})

//上传主图
var mainImg;
$('#avatarInput').on('change', function(e) {
    var filemaxsize = 1024 * 5;//5M
    var target = $(e.target);
    var Size = target[0].files[0].size / 1024;
    if(Size > filemaxsize) {
        alert('图片过大，请重新选择!');
        $(".avatar-wrapper").childre().remove;
        return false;
    }
    if(!this.files[0].type.match(/image.*/)) {
        alert('请选择正确的图片!')
    } else {
        var filename = document.querySelector("#avatar-name");
        var texts = document.querySelector("#avatarInput").value;
        var teststr = texts; //你这里的路径写错了
        testend = teststr.match(/[^\\]+\.[^\(]+/i); //直接完整文件名的
        filename.innerHTML = testend;
    }

});

var ifEdit = '';//1为编辑0为添加
$('#update').click(function () {
    ifEdit = 0;
})
$('#update2').click(function () {
    ifEdit = 1;
})
$(".avatar-save").on("click", function() {
    var img_lg = document.getElementById('imageHead');
    // 截图小的显示框内的内容
    html2canvas(img_lg, {
        allowTaint: true,
        taintTest: false,
        onrendered: function(canvas) {
            canvas.id = "mycanvas";
            //生成base64图片数据
            var dataUrl = canvas.toDataURL("image/jpeg");
            var newImg = document.createElement("img");
            newImg.src = dataUrl;
            imagesAjax(dataUrl)
        }
    });
})

function imagesAjax(src) {
    var data = {};
    data.img = src;
    data.jid = $('#jid').val();
    mainImg = src;

    $.ajax({
        url:'/crm/image/uploadImage.json',
        data:{
            filed:mainImg,
        },
        dataType:'json',
        type:'post',
        success:function(data){
            if(data.code==1){
                if(ifEdit==0){
                    $('#mainImg').show();
                    $('#mainImg').attr('src',data.datas.path);
                    $('#update').html('更换')
                }else{
                    $('#mainImg2').show();
                    $('#mainImg2').attr('src',data.datas.path);
                    $('#update2').html('更换')
                }
            }
        }
    })
}

// //保存修改
$('#save').click(function(){
    if($('#avatar-name').html()==""){
        alert('请选择图片');
    }else{
        $('#save').attr('data-dismiss','modal')
    }
})



// //保存修改
$('#save2').click(function(){
    if($('#avatar-name').html()==""){
        alert('请选择图片');
    }else{
        $('#save2').attr('data-dismiss','modal')
    }
})

//编辑分类
$('#editSave').click(function () {
    $.ajax({
        url:'/crm/goodsCategoryC/edit.json',
        dataType:'json',
        data:{
            token:localStorage.getItem('crmtoken'),
            categoryId:categoryId,
            name:$('#editName').val(),
            imgUrl:$('#mainImg2').attr('src'),
            categoryType:1,
            summary:$('#editsummary').val(),
            linkUrl:$('#editlinkUrl').val(),
            sort:$('#editNumber').val(),
            isValid:$('#editState').val(),
        },
        type:'post',
        success:function(data){
            if(data.code==0){
                alert(data.msg)
                return;
            }
            if(data.code==-1){
                window.parent.location.href="/crm/login.jsp"
            }
            if(data.code==1){
                alert('修改成功');
                $('#myModal4').hide();
                $('#myModal4').removeClass('fade in');
                $('#myModal4').addClass('fade');
                $('#myModal4').attr('aria-hidden',true);
                $('#myModal4').css('display','none');
                $('.modal-backdrop').css('display','none');
                $('#myModal4 input').val('');
                page=1;
                doAjax();
            }
        }
    })
})

$(function () {

    'use strict';

    var console = window.console || { log: function () {} },
        $alert = $('.docs-alert'),
        $message = $alert.find('.message'),
        showMessage = function (message, type) {
            $message.text(message);

            if (type) {
                $message.addClass(type);
            }

            $alert.fadeIn();

            setTimeout(function () {
                $alert.fadeOut();
            }, 3000);
        };


    (function () {
        var $image = $('.img-container > img'),
            $dataX = $('#dataX'),
            $dataY = $('#dataY'),
            $dataHeight = $('#dataHeight'),
            $dataWidth = $('#dataWidth'),
            $dataRotate = $('#dataRotate'),
            options = {
                aspectRatio: 13 / 4,
                preview: '.img-preview',
                crop: function (data) {
                    $dataX.val(Math.round(data.x));
                    $dataY.val(Math.round(data.y));
                    $dataHeight.val(Math.round(data.height));
                    $dataWidth.val(Math.round(data.width));
                    $dataRotate.val(Math.round(data.rotate));
                }
            };

        $image.on({
            'build.cropper': function (e) {
                console.log(e.type);
            },
            'built.cropper': function (e) {
                console.log(e.type);
            },
            'dragstart.cropper': function (e) {
                console.log(e.type, e.dragType);
            },
            'dragmove.cropper': function (e) {
                console.log(e.type, e.dragType);
            },
            'dragend.cropper': function (e) {
                console.log(e.type, e.dragType);
            },
            'zoomin.cropper': function (e) {
                console.log(e.type);
            },
            'zoomout.cropper': function (e) {
                console.log(e.type);
            }
        }).cropper(options);


        // Methods
        $(document.body).on('click', '[data-method]', function () {
            var data = $(this).data(),
                $target,
                result;

            if (data.method) {
                data = $.extend({}, data); // Clone a new one

                if (typeof data.target !== 'undefined') {
                    $target = $(data.target);

                    if (typeof data.option === 'undefined') {
                        try {
                            data.option = JSON.parse($target.val());
                        } catch (e) {
                            console.log(e.message);
                        }
                    }
                }

                result = $image.cropper(data.method, data.option);

                if (data.method === 'getCroppedCanvas') {
                    $('#getCroppedCanvasModal').modal().find('.modal-body').html(result);
                }

                if ($.isPlainObject(result) && $target) {
                    try {
                        $target.val(JSON.stringify(result));
                    } catch (e) {
                        console.log(e.message);
                    }
                }

            }
        }).on('keydown', function (e) {

            switch (e.which) {
                case 37:
                    e.preventDefault();
                    $image.cropper('move', -1, 0);
                    break;

                case 38:
                    e.preventDefault();
                    $image.cropper('move', 0, -1);
                    break;

                case 39:
                    e.preventDefault();
                    $image.cropper('move', 1, 0);
                    break;

                case 40:
                    e.preventDefault();
                    $image.cropper('move', 0, 1);
                    break;
            }

        });


        // Import image
        var $inputImage = $('#inputImage'),
            URL = window.URL || window.webkitURL,
            blobURL;

        if (URL) {
            $inputImage.change(function () {
                var files = this.files,
                    file;

                if (files && files.length) {
                    file = files[0];

                    if (/^image\/\w+$/.test(file.type)) {
                        blobURL = URL.createObjectURL(file);
                        $image.one('built.cropper', function () {
                            URL.revokeObjectURL(blobURL); // Revoke when load complete
                        }).cropper('reset', true).cropper('replace', blobURL);
                        $inputImage.val('');
                    } else {
                        showMessage('Please choose an image file.');
                    }
                }
            });
        } else {
            $inputImage.parent().remove();
        }


        // Options
        $('.docs-options :checkbox').on('change', function () {
            var $this = $(this);

            options[$this.val()] = $this.prop('checked');
            $image.cropper('destroy').cropper(options);
        });


        // Tooltips
        $('[data-toggle="tooltip"]').tooltip();

    }());

});

